import Vue from "vue";
import Vuex from "vuex";
import * as permissionApi from "@/api/permission"
//引入递归路由的方法
import recursionRoutes from "@/utils/recursionRoutes"
//引入项目所有的路由
import allRoutes from "@/router/generateRoutes"
//引入动态路由
import dynamicRoutes from "@/router/dynamicRoutes"

import router from "@/router"
//持久化存储
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userMenu: [],
    userInfo:{},
    currentProduct:{}//当前充值的产品对象
  },
  getters: {},
  mutations: {
    SET_MENULIST(state,payload){
      state.userMenu = [...payload]

      //动态添加路由，引入dynamic路由，进行匹配path==='/'这个对象，让我们的用户路由中的结果，成为i这个对象的children
      let target = dynamicRoutes.find(route=>route.path==="/");

      target.children = [...target.children, ...payload]
      //动态地将路由添加到根路由的routes选项中
      router.addRoute(target)
    },
    SET_USERINFO(state,payload){
      state.userInfo = payload
    },
    //设置当前充值的产品
    SET_CURRENT_PRODUCT(state,payload){
      state.currentProduct = payload 
    }
  },
  actions: {
    //请求菜单数据
    //1.计算出用户（role）的菜单
    //2.计算出当前这个角色的合法路由
    async FETCH_MENULIST(context,payload){
      return permissionApi.getMenuList().then(res=>{
        console.log(res);
        let {menuList} = res.data;
        //调用recursionRoutes
        let userRoutes = recursionRoutes(allRoutes[0].children,menuList);
        console.log(userRoutes);
        //让mutation进行处理
        context.commit("SET_MENULIST",userRoutes);
      })
    }
  },
  modules: {},
  /* vuex数据持久化配置 */
  plugins: [
    createPersistedState({
      // 存储方式：localStorage、sessionStorage、cookies
      storage: window.localStorage,
      // 存储的 key 的key值
      key: "wqj-persist",
      paths:['userInfo','currentProduct']
    })
  ]
});
